from django.shortcuts import render,redirect,HttpResponse
import hashlib

from test1 import models
# Create your views here.

def hashhandle(str):
    md5 = hashlib.md5()
    md5.update(bytes(str,encoding='utf8'))
    return md5.hexdigest()


def login(request):
    context = {}
    if request.method =='GET':
        return render(request,'login.html')
    if request.method == 'POST':
        username = request.POST.get('username',None)
        password = request.POST.get('password',None)
        userinfo = models.UserInfo.objects.filter(username=username).first()
        if userinfo == None:
            context['error'] = '没有该用户!请重新输入'
            return render(request,'login.html',context)
        elif userinfo and hashhandle(password) == userinfo.password:
            request.session['username']=username
            return redirect('/')
        else:
            context['error'] ='密码错误'
            return render(request,'login.html',context)



def index(request):
    context = {}
    if request.session.get('username',None) == None:
        return redirect('/login')
    else:
        context['username'] = request.session.get('username')
    return render(request,'index.html',context)

def register(request):
    context = {}
    if request.method == 'GET':
        return render(request,'register.html')
    if request.method == 'POST':
        username = request.POST.get('username',None)
        password = request.POST.get('password',None)
        if models.UserInfo.objects.filter(username=username):
            context['error'] = '用户已存在'
            return render(request,'register.html',context)
        else:
            password_hash_handle = hashlib.md5()
            password_hash_handle.update(bytes(password,encoding='utf8'))
            print(password_hash_handle.hexdigest())
            models.UserInfo.objects.create(username=username,password=password_hash_handle.hexdigest())
            request.session['username']=username
            return redirect('/')